'use client';

import { useState, useRef, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import {
  Upload,
  File,
  FileText,
  Search,
  Trash2,
  Download,
  RefreshCw,
  X,
  CheckCircle,
  AlertCircle,
  Loader2,
  Eye,
  MoreVertical,
} from 'lucide-react';
import {
  useDocuments,
  useSelectedDocument,
  useUploadProgress,
  useDocumentActions,
  useUser,
} from '@/store';
import { Document } from '@/types';
import { cn } from '@/lib/utils';

// 辅助函数：安全地渲染metadata值
const renderMetadataValue = (value: unknown): string => {
  if (value === null || value === undefined) return '';
  return String(value);
};

interface DocumentItemProps {
  document: Document;
  isSelected: boolean;
  onSelect: (doc: Document) => void;
  onDelete: (id: string) => void;
}

function DocumentItem({
  document,
  isSelected,
  onSelect,
  onDelete,
}: DocumentItemProps) {
  const [isDeleting, setIsDeleting] = useState(false);

  const handleDelete = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!confirm('确定要删除这个文档吗？')) return;

    setIsDeleting(true);
    try {
      const response = await fetch(`/api/documents/${document.id}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        onDelete(document.id);
      } else {
        throw new Error('删除失败');
      }
    } catch (error) {
      console.error('删除文档失败:', error);
      alert('删除文档失败，请重试');
    } finally {
      setIsDeleting(false);
    }
  };

  const getFileIcon = (type: string) => {
    if (type.includes('pdf'))
      return <FileText className='h-4 w-4 text-red-500' />;
    if (type.includes('text'))
      return <File className='h-4 w-4 text-blue-500' />;
    if (type.includes('word'))
      return <FileText className='h-4 w-4 text-blue-600' />;
    return <File className='h-4 w-4 text-gray-500' />;
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'processed':
        return (
          <Badge variant='default' className='text-xs'>
            已处理
          </Badge>
        );
      case 'processing':
        return (
          <Badge variant='secondary' className='text-xs'>
            处理中
          </Badge>
        );
      case 'failed':
        return (
          <Badge variant='destructive' className='text-xs'>
            失败
          </Badge>
        );
      default:
        return (
          <Badge variant='outline' className='text-xs'>
            待处理
          </Badge>
        );
    }
  };

  return (
    <Card
      className={cn(
        'p-3 cursor-pointer transition-all hover:shadow-md',
        isSelected ? 'ring-2 ring-primary' : ''
      )}
      onClick={() => onSelect(document)}
    >
      <div className='flex items-start gap-3'>
        <div className='flex-shrink-0 mt-1'>
          {getFileIcon(document.file_type)}
        </div>

        <div className='flex-1 min-w-0'>
          <div className='flex items-start justify-between gap-2'>
            <div className='flex-1 min-w-0'>
              <h4
                className='font-medium text-sm truncate'
                title={document.title}
              >
                {document.title}
              </h4>
              <p className='text-xs text-muted-foreground mt-1'>
                {document.file_size
                  ? `${(document.file_size / 1024).toFixed(1)} KB`
                  : ''}{' '}
                •{new Date(document.created_at).toLocaleDateString()}
              </p>
            </div>

            <div className='flex items-center gap-1'>
              {getStatusBadge(document.status || 'pending')}
              <Button
                variant='ghost'
                size='sm'
                className='h-6 w-6 p-0 opacity-0 group-hover:opacity-100'
                onClick={handleDelete}
                disabled={isDeleting}
              >
                {isDeleting ? (
                  <Loader2 className='h-3 w-3 animate-spin' />
                ) : (
                  <Trash2 className='h-3 w-3' />
                )}
              </Button>
            </div>
          </div>

          {document.content && (
            <p className='text-xs text-muted-foreground mt-2 line-clamp-2'>
              {document.content.substring(0, 100)}...
            </p>
          )}

          {(() => {
            const chunksValue = renderMetadataValue(document.metadata?.chunks);
            const embeddingModelValue = renderMetadataValue(document.metadata?.embedding_model);
            
            if (!chunksValue) return null;
            
            return (
              <div className='flex items-center gap-2 mt-2'>
                <Badge variant='outline' className='text-xs'>
                  {chunksValue} 个片段
                </Badge>
                {embeddingModelValue && (
                  <Badge variant='outline' className='text-xs'>
                    {embeddingModelValue}
                  </Badge>
                )}
              </div>
            );
          })()}
        </div>
      </div>
    </Card>
  );
}

function UploadArea() {
  const user = useUser();
  const uploadProgress = useUploadProgress();
  const { addDocument, setUploadProgress } = useDocumentActions();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragging, setIsDragging] = useState(false);

  const handleFileSelect = useCallback(
    async (files: FileList) => {
      if (!files.length || !user) return;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 文件类型检查
        const allowedTypes = [
          'text/plain',
          'application/pdf',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ];
        if (!allowedTypes.includes(file.type)) {
          alert(`不支持的文件类型: ${file.name}`);
          continue;
        }

        // 文件大小检查 (10MB)
        if (file.size > 10 * 1024 * 1024) {
          alert(`文件过大: ${file.name} (最大10MB)`);
          continue;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('userId', user.id);

        try {
          setUploadProgress({ [file.name]: 0 });

          const response = await fetch('/api/documents/upload', {
            method: 'POST',
            body: formData,
          });

          const data = await response.json();

          if (data.success) {
            setUploadProgress({ [file.name]: 100 });
            addDocument(data.data);

            // 清除进度
            setTimeout(() => {
              setUploadProgress({});
            }, 2000);
          } else {
            throw new Error(data.message || '上传失败');
          }
        } catch (error) {
          console.error('上传失败:', error);
          alert(`上传失败: ${file.name}`);
          setUploadProgress({});
        }
      }
    },
    [user, addDocument, setUploadProgress]
  );

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      setIsDragging(false);

      const files = e.dataTransfer.files;
      handleFileSelect(files);
    },
    [handleFileSelect]
  );

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleClick = () => {
    fileInputRef.current?.click();
  };

  const hasUploading = Object.keys(uploadProgress).length > 0;

  return (
    <div className='space-y-4'>
      <div
        className={cn(
          'border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors',
          isDragging
            ? 'border-primary bg-primary/5'
            : 'border-muted-foreground/25 hover:border-primary/50'
        )}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onClick={handleClick}
      >
        <Upload className='h-8 w-8 mx-auto mb-2 text-muted-foreground' />
        <p className='text-sm font-medium mb-1'>点击上传或拖拽文件到此处</p>
        <p className='text-xs text-muted-foreground'>
          支持 PDF、Word、TXT 格式，最大 10MB
        </p>

        <input
          ref={fileInputRef}
          type='file'
          multiple
          accept='.pdf,.doc,.docx,.txt'
          className='hidden'
          onChange={e => e.target.files && handleFileSelect(e.target.files)}
        />
      </div>

      {/* 上传进度 */}
      {hasUploading && (
        <div className='space-y-2'>
          {Object.entries(uploadProgress).map(([filename, progress]) => (
            <div key={filename} className='flex items-center gap-2 text-sm'>
              <File className='h-4 w-4 flex-shrink-0' />
              <span className='flex-1 truncate'>{filename}</span>
              <span className='text-xs text-muted-foreground'>{progress}%</span>
              {progress === 100 ? (
                <CheckCircle className='h-4 w-4 text-green-500' />
              ) : (
                <Loader2 className='h-4 w-4 animate-spin' />
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export function DocumentPanel() {
  const user = useUser();
  const documents = useDocuments();
  const selectedDocument = useSelectedDocument();
  const { setDocuments, setSelectedDocument, deleteDocument } =
    useDocumentActions();

  const [searchQuery, setSearchQuery] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [showUpload, setShowUpload] = useState(false);

  // 加载文档列表
  const loadDocuments = async () => {
    if (!user) return;

    setIsLoading(true);
    try {
      const response = await fetch(
        `/api/documents/upload?userId=${user.id}&limit=50`
      );
      const data = await response.json();

      if (data.success) {
        setDocuments(data.data);
      }
    } catch (error) {
      console.error('加载文档失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 搜索文档
  const handleSearch = async () => {
    if (!searchQuery.trim() || !user) {
      loadDocuments();
      return;
    }

    setIsLoading(true);
    try {
      const response = await fetch('/api/search', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          query: searchQuery,
          type: 'text',
          userId: user.id,
          limit: 20,
        }),
      });

      const data = await response.json();

      if (data.success) {
        setDocuments(data.data);
      }
    } catch (error) {
      console.error('搜索失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleDocumentSelect = (doc: Document) => {
    setSelectedDocument(doc);
  };

  const handleDocumentDelete = (id: string) => {
    deleteDocument(id);
    if (selectedDocument?.id === id) {
      setSelectedDocument(null);
    }
  };

  const filteredDocuments = Array.isArray(documents)
    ? documents.filter(
        doc =>
          doc.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
          (doc.content &&
            doc.content.toLowerCase().includes(searchQuery.toLowerCase()))
      )
    : [];

  return (
    <div className='flex flex-col h-full'>
      {/* 头部 */}
      <div className='p-4 border-b border-border'>
        <div className='flex items-center justify-between mb-4'>
          <h2 className='font-semibold'>文档管理</h2>
          <div className='flex items-center gap-2'>
            <Button
              variant='outline'
              size='sm'
              onClick={loadDocuments}
              disabled={isLoading}
            >
              {isLoading ? (
                <Loader2 className='h-4 w-4 animate-spin' />
              ) : (
                <RefreshCw className='h-4 w-4' />
              )}
            </Button>
            <Button
              variant={showUpload ? 'secondary' : 'default'}
              size='sm'
              onClick={() => setShowUpload(!showUpload)}
            >
              {showUpload ? (
                <X className='h-4 w-4' />
              ) : (
                <Upload className='h-4 w-4' />
              )}
            </Button>
          </div>
        </div>

        {/* 搜索 */}
        <div className='flex gap-2'>
          <Input
            placeholder='搜索文档...'
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && handleSearch()}
            className='flex-1'
          />
          <Button
            variant='outline'
            size='sm'
            onClick={handleSearch}
            disabled={isLoading}
          >
            <Search className='h-4 w-4' />
          </Button>
        </div>

        {/* 统计信息 */}
        <div className='flex items-center gap-4 mt-3 text-sm text-muted-foreground'>
          <span>共 {documents.length} 个文档</span>
          {searchQuery && <span>找到 {filteredDocuments.length} 个结果</span>}
        </div>
      </div>

      {/* 上传区域 */}
      {showUpload && (
        <div className='p-4 border-b border-border'>
          <UploadArea />
        </div>
      )}

      {/* 文档列表 */}
      <ScrollArea className='flex-1'>
        <div className='p-4 space-y-3'>
          {isLoading ? (
            <div className='flex items-center justify-center py-8'>
              <Loader2 className='h-6 w-6 animate-spin' />
            </div>
          ) : filteredDocuments.length === 0 ? (
            <div className='text-center py-8'>
              <FileText className='h-12 w-12 mx-auto mb-4 text-muted-foreground' />
              <h3 className='font-medium mb-2'>
                {searchQuery ? '未找到相关文档' : '暂无文档'}
              </h3>
              <p className='text-sm text-muted-foreground mb-4'>
                {searchQuery
                  ? '尝试使用其他关键词搜索'
                  : '上传文档开始使用RAG功能'}
              </p>
              {!searchQuery && (
                <Button variant='outline' onClick={() => setShowUpload(true)}>
                  <Upload className='h-4 w-4 mr-2' />
                  上传文档
                </Button>
              )}
            </div>
          ) : (
            filteredDocuments.map(doc => (
              <DocumentItem
                key={doc.id}
                document={doc}
                isSelected={selectedDocument?.id === doc.id}
                onSelect={handleDocumentSelect}
                onDelete={handleDocumentDelete}
              />
            ))
          )}
        </div>
      </ScrollArea>

      {/* 选中文档详情 */}
      {selectedDocument && (
        <div className='border-t border-border p-4'>
          <div className='flex items-center justify-between mb-2'>
            <h4 className='font-medium text-sm'>文档详情</h4>
            <Button
              variant='ghost'
              size='sm'
              className='h-6 w-6 p-0'
              onClick={() => setSelectedDocument(null)}
            >
              <X className='h-3 w-3' />
            </Button>
          </div>

          <div className='space-y-2 text-xs'>
            <div>
              <span className='font-medium'>文件名:</span>
              <span className='ml-2 text-muted-foreground'>
                {selectedDocument.title}
              </span>
            </div>
            <div>
              <span className='font-medium'>类型:</span>
              <span className='ml-2 text-muted-foreground'>
                {selectedDocument.file_type}
              </span>
            </div>
            <div>
              <span className='font-medium'>大小:</span>
              <span className='ml-2 text-muted-foreground'>
                {selectedDocument.file_size
                  ? `${(selectedDocument.file_size / 1024).toFixed(1)} KB`
                  : '未知'}
              </span>
            </div>
            <div>
              <span className='font-medium'>状态:</span>
              <span className='ml-2'>
                {selectedDocument.status === 'processed' ? (
                  <Badge variant='default' className='text-xs'>
                    已处理
                  </Badge>
                ) : selectedDocument.status === 'processing' ? (
                  <Badge variant='secondary' className='text-xs'>
                    处理中
                  </Badge>
                ) : selectedDocument.status === 'failed' ? (
                  <Badge variant='destructive' className='text-xs'>
                    失败
                  </Badge>
                ) : (
                  <Badge variant='outline' className='text-xs'>
                    待处理
                  </Badge>
                )}
              </span>
            </div>
            {(() => {
              const chunksValue = renderMetadataValue(selectedDocument.metadata?.chunks);
              if (!chunksValue) return null;
              
              return (
                <div>
                  <span className='font-medium'>向量片段:</span>
                  <span className='ml-2 text-muted-foreground'>
                    {chunksValue} 个
                  </span>
                </div>
              );
            })()}
          </div>
        </div>
      )}
    </div>
  );
}
